<?php

namespace App\Http\Repositories\Base;

use App\Http\Repositories\BaseRepository as Repository;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class ImagesRepository extends Repository
{
    const THUMB_WIDTH = 100;
    const THUMB_HEIGHT = 100;

//    const SAVE_PATH = storage_path('app/public/');
//    const SAVE_PATH = 'd:/Users/Administrator/Desktop/文件/img/thumb/';
    const INSERT_PATH = 'd:\Users\Administrator\Desktop\文件\img\e1803f2985203acf433ef35874201cfb.png';

    private $image;
    private $storage;
    public function __construct(Image $image, Storage $storage)
    {
        $this->image = $image;
        $this->storage = $storage;
    }

    /**
     * 缩略图
     * @param $file
     * @return string
     */
    public function thumb($file){
        $name = md5($file.time()).'.'.$file->getClientOriginalExtension();
        $save_path = storage_path('app/public/').$name;

        $img = $this->image
                    ::make($file)//打开图片
                    ->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)//调整宽高
//                    ->insert(self::INSERT_PATH,'bottom-right')//插入水印
                    ->save($save_path);//保存

//        //插入文字
//        $img->text('This is text', 250, 250, function ($font) {});
        return $name;
    }

    /**
     * 图片上传
     * @param $data
     * @return array
     */
    public function uploadImage($data)
    {

//        //获取文件数据
//        $data['file_name'] = $file->getClientOriginalName();
//        $data['size'] = $file->getClientSize();
//        $data['mime_type'] = $file->getClientMimeType();
//        $img_info= getimagesize($file);
//        $data['width'] = $img_info[0];
//        $data['height'] = $img_info[1];

        is_array($data['image']) ? $file =$data['image'] : $file[] =$data['image'];

        $res = [
            'image_path' => '',
            'thumb_path' => ''
        ];

        foreach ($file as $k => $v) {

            if ($v->isValid()) {
                $realpath = $v->getRealPath();
                $ext = $v->getClientOriginalExtension();
                $md5 = $data['md5'] = md5_file($realpath).'.'.$ext;
                //上传原图
                $this->storage::disk('public')->put($md5, file_get_contents($realpath));
                //上传缩略图
                $thumb = $this->thumb($v);
                //返回路径
                (strlen($res['image_path']) > 0) ? ($res['image_path'] .= ';'.$md5) : ($res['image_path'] .= $md5);
                (strlen($res['thumb_path']) > 0) ? ($res['thumb_path'] .= ';'.$thumb) : ($res['thumb_path'] .= $thumb);
            }

        }

        return $res;
    }
}
